package com.ruoyi.web.controller.work;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.ICommonEnum;
import com.ruoyi.common.enums.MediaType;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.service.ISysUserOnlineService;
import com.ruoyi.work.service.PriceType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.common.BasicCodeDeleteHandler;
import com.ruoyi.work.domain.*;
import com.ruoyi.work.service.*;
import org.apache.ibatis.session.SqlSession;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.*;

/**
 * 稿件管理Controller
 *
 * @author ruoyi
 * @date 2021-12-26
 */
@Controller
@RequestMapping({"/work/paper", "/work/netpaper", "/work/apppaper", "/work/flowpaper", "/work/planepaper", "/work/wbpaper", "/work/wxpaper"})
public class WorkPaperController extends BaseController {
    private String prefix = "work/paper";

    @Autowired
    private IWorkPaperService workPaperService;
    @Autowired
    private IWorkMediaWbService workMediaWbService;
    @Autowired
    private IWorkMediaWxService workMediaWxService;
    @Autowired
    private IWorkCustomerService workCustomerService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SqlSession sqlSession;

    @RequiresPermissions(value = {"work:paper:view", "work:apppaper:view", "work:netpaper:view", "work:flowpaper:view", "work:planepaper:view", "work:wbpaper:view", "work:wxpaper:view"}, logical = Logical.OR)
    @GetMapping()
    public String paper() {
        return prefix + "/paper";
    }

    /**
     * 查询稿件管理列表
     */
    @RequiresPermissions("work:paper:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WorkPaper workPaper) {
        startPage();
        List<WorkPaper> list = workPaperService.selectWorkPaperList(workPaper);
        return getDataTable(list);
    }

    /**
     * 查询稿件管理列表
     */
    @RequiresPermissions("work:paper:list")
    @PostMapping("/grouplist")
    @ResponseBody
    public TableDataInfo grouplist(WorkPaper workPaper) {
        startPage();
        List<WorkPaper> list = workPaperService.selectWorkPaperGroupList(workPaper);
        return getDataTable(list);
    }

    /**
     * 查询稿件管理列表
     */
    @RequiresPermissions(value = {"work:netpaper:list", "work:apppaper:list", "work:flowpaper:list", "work:planepaper:list", "work:wbpaper:list", "work:wxpaper:list"}, logical = Logical.OR)
    @PostMapping("/list/{paperType}")
    @ResponseBody
    public TableDataInfo list(@PathVariable("paperType") String paperType, WorkPaper workPaper) {
        startPage();
        workPaper.setPaperType(paperType);
        List<WorkPaper> list = workPaperService.selectWorkPaperLists(workPaper);
        return getDataTable(list);
    }

    /**
     * 查询稿件管理列表
     */
    @RequiresPermissions(value = {"work:netpaper:list", "work:apppaper:list", "work:flowpaper:list", "work:planepaper:list", "work:wbpaper:list", "work:wxpaper:list"}, logical = Logical.OR)
    @PostMapping("/grouplist/{paperType}")
    @ResponseBody
    public TableDataInfo grouplist(@PathVariable("paperType") String paperType, WorkPaper workPaper) {
        startPage();
        workPaper.setPaperType(paperType);
        List<WorkPaper> list = workPaperService.selectWorkPaperGroupLists(workPaper);
        return getDataTable(list);
    }

    /**
     * 导出稿件管理列表
     */
    @RequiresPermissions("work:paper:export")
    @Log(title = "稿件管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WorkPaper workPaper) {
        List<WorkPaper> list = workPaperService.selectWorkPaperList(workPaper);
        ExcelUtil<WorkPaper> util = new ExcelUtil<WorkPaper>(WorkPaper.class);
        return util.exportExcel(list, "稿件管理数据");
    }

    /**
     * 导出稿件管理列表
     */
    @RequiresPermissions("work:paper:export")
    @Log(title = "稿件管理", businessType = BusinessType.EXPORT)
    @PostMapping("/groupexport")
    @ResponseBody
    public AjaxResult groupexport(WorkPaper workPaper) {
        workPaper.setBatchId(0L);
        List<WorkPaper> list = workPaperService.selectWorkPaperList(workPaper);
        ExcelUtil<WorkPaper> util = new ExcelUtil<WorkPaper>(WorkPaper.class);
        return util.exportExcel(list, "稿件管理数据");
    }

    /**
     * 导出稿件管理列表
     */
    @RequiresPermissions("work:paper:export")
    @Log(title = "稿件管理", businessType = BusinessType.EXPORT)
    @RequestMapping("/mediaexport/{paperType}")
    @ResponseBody
    public AjaxResult mediaexport(@PathVariable("paperType") String paperType, WorkPaper workPaper) {
        workPaper.setPaperType(paperType);
        List<WorkPaper> list = workPaperService.selectWorkPaperList(workPaper);
        ExcelUtil<WorkPaper2> util = new ExcelUtil<WorkPaper2>(WorkPaper2.class);
        List<WorkPaper2> lst = new ArrayList<>();

        list.forEach((w) -> {
            WorkPaper2 w2 = new WorkPaper2();
            w2.setPaperType(w.getPaperType());
            w2.setPaperName(w.getPaperName());
            w2.setCustomerName(w.getCustomerName());
            w2.setCompanyName(w.getCompanyName());
            w2.setMediaName(w.getMediaName());
            w2.setPlatform(w.getPlatform());
            w2.setMediaCreate(w.getMediaCreate());
            w2.setPublishLink(w.getPublishLink());
            w2.setPublishDate(w.getPublishDate());
            w2.setPaperPrice(w.getPaperPrice());
            w2.setPaperStatus(w.getPaperStatus());
            w2.setContacts(w.getContacts());
            w2.setBelong(w.getBelong());
            w2.setActualCost(w.getActualCost());
            w2.setPayTime(w.getPayTime());
            w2.setCreateTime(w.getCreateTime());

            lst.add(w2);
        });

        return util.exportExcel(lst, "稿件管理数据");
    }

    /**
     * 导出稿件管理列表
     */
    @RequiresPermissions("work:paper:export")
    @Log(title = "稿件管理", businessType = BusinessType.EXPORT)
    @RequestMapping("/mediagroupexport/{paperType}")
    @ResponseBody
    public AjaxResult mediagroupexport(@PathVariable("paperType") String paperType, WorkPaper workPaper) {
        workPaper.setPaperType(paperType);
        workPaper.setBatchId(0L);
        List<WorkPaper> list = workPaperService.selectWorkPaperList(workPaper);
        ExcelUtil<WorkPaper2> util = new ExcelUtil<WorkPaper2>(WorkPaper2.class);
        List<WorkPaper2> lst = new ArrayList<>();

        list.forEach((w) -> {
            WorkPaper2 w2 = new WorkPaper2();
            w2.setPaperType(w.getPaperType());
            w2.setPaperName(w.getPaperName());
            w2.setCustomerName(w.getCustomerName());
            w2.setCompanyName(w.getCompanyName());
            w2.setMediaName(w.getMediaName());
            w2.setPlatform(w.getPlatform());
            w2.setMediaCreate(w.getMediaCreate());
            w2.setPublishLink(w.getPublishLink());
            w2.setPublishDate(w.getPublishDate());
            w2.setPaperPrice(w.getPaperPrice());
            w2.setPaperStatus(w.getPaperStatus());
            w2.setContacts(w.getContacts());
            w2.setBelong(w.getBelong());
            w2.setActualCost(w.getActualCost());
            w2.setPayTime(w.getPayTime());
            w2.setCreateTime(w.getCreateTime());

            lst.add(w2);
        });

        return util.exportExcel(lst, "稿件管理数据");
    }

    /**
     * 新增稿件管理
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存稿件管理
     */
    @RequiresPermissions("work:paper:add")
    @Log(title = "稿件管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Wp wp) {
        Long millisecond = Instant.now().toEpochMilli();
        wp.getPapers().forEach((entity) -> {
            entity.setCustomerId(wp.getCustomerId());
            entity.setPaperName(wp.getPaperName());
            entity.setOriginalLink(wp.getOriginalLink());
            entity.setPaybackPeriod(wp.getPaybackPeriod());
            entity.setRemark(wp.getRemark());
            entity.setCost(entity.getPaperPrice());
            entity.setActualCost(entity.getPaperPrice());
            entity.setPriceType(wp.getPriceType());
            entity.setCreateBy(getLoginName());
            entity.setBelong(getUserName());
            entity.setUploadFile(wp.getUploadFile());
            // entity.setBatchId(millisecond);
            workPaperService.insertWorkPaper(entity);
        });
        return toAjax(true);
    }

    /**
     * 修改稿件管理
     */
    @RequiresPermissions("work:paper:edit")
    @GetMapping("/edit/{paperId}")
    public String edit(@PathVariable("paperId") Long paperId, ModelMap mmap) {
        WorkPaper workPaper = workPaperService.selectWorkPaperByPaperId(paperId);
        mmap.put("workPaper", workPaper);
        return prefix + "/edit";
    }

    /**
     * 修改保存稿件管理
     */
    @RequiresPermissions("work:paper:edit")
    @Log(title = "稿件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WorkPaper workPaper) {

        workPaper.setUpdateBy(getLoginName());
        return toAjax(workPaperService.updateWorkPaper(workPaper));
    }

    /**
     * 删除稿件管理
     */
    @RequiresPermissions("work:paper:remove")
    @Log(title = "稿件管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(workPaperService.deleteWorkPaperByPaperIds(ids));
    }

    /**
     * 批量改价
     *
     * @param ids
     * @param price
     * @return
     */
    @RequiresPermissions("work:paper:changeprice")
    @Log(title = "稿件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/changeprice")
    @ResponseBody
    public AjaxResult changeprice(String[] ids, BigDecimal price) {

        workPaperService.selectWorkPaperByPaperIds(ids).forEach(paper -> {

            paper.setActualPrice(price);
            workPaperService.updateWorkPaper(paper);

        });

        return AjaxResult.success();
    }

    /**
     * 批量设置客户
     *
     * @param ids
     * @param customer
     * @return
     */
    @RequiresPermissions("work:paper:setcustomer")
    @Log(title = "稿件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/setcustomer")
    @ResponseBody
    public AjaxResult setcustomer(String[] ids, String customer) {
        List<WorkPaper> list = workPaperService.selectWorkPaperByPaperIds(ids);
        if (list.stream().anyMatch(r -> !r.getCreateBy().equals(getLoginName()))) {
            return AjaxResult.error("不能修改不属于自己的稿件客户！");
        }
        WorkCustomer workCustomer = new WorkCustomer();
        workCustomer.setCreateBy(getLoginName());
        workCustomer.setCustomerName(customer.trim());
        workCustomer = workCustomerService.selectWorkCustomerList(workCustomer).stream().findFirst().orElse(null);
        if (workCustomer == null) {
            return AjaxResult.error("客户不存在！");
        }
        WorkCustomer finalWorkCustomer = workCustomer;
        list.forEach(paper -> {

            paper.setCustomerId(finalWorkCustomer.getCustomerId());
            paper.setCustomerName(finalWorkCustomer.getCustomerName());
            paper.setCompanyName(finalWorkCustomer.getCompanyName());
            workPaperService.updateWorkPaper(paper);


        });

        return AjaxResult.success();
    }

    /**
     * 批量领取
     *
     * @param ids
     * @param
     * @return
     */
    @RequiresPermissions("work:paper:setmedia")
    @Log(title = "稿件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/setmedia")
    @ResponseBody
    public AjaxResult setmedia(String[] ids) {

        workPaperService.selectWorkPaperByPaperIds(ids).forEach(paper -> {
            paper.setMediaCreate(getUserName());
            paper.setMediaCreateLogin(getLoginName());
            workPaperService.updateWorkPaper(paper);
        });

        return AjaxResult.success();
    }

    /**
     * 批量请款
     *
     * @param ids
     * @param requestId
     * @return
     */
    @RequiresPermissions("work:paper:fund")
    @Log(title = "稿件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/fund")
    @ResponseBody
    public AjaxResult fund(String[] ids, Long requestId) {

        List<WorkPaper> lst = workPaperService.selectWorkPaperByPaperIds(ids);
        Optional<WorkPaper> opt = lst.parallelStream().filter(w -> StringUtils.isEmpty(w.getMediaCreateLogin())).findFirst();
        if (opt.isPresent()) {
            return AjaxResult.error("请先领取稿件！");
        }
        opt = lst.parallelStream().filter(w -> !w.getMediaCreateLogin().equals(getLoginName())).findFirst();
        if (opt.isPresent()) {
            return AjaxResult.error("只能操作自己领取的稿件！");
        }
        lst.forEach(paper -> {
            paper.setRequestId(requestId);
            workPaperService.updateWorkPaper(paper);
        });

        return AjaxResult.success();
    }

    /**
     * 批量刊登
     *
     * @param ids
     * @param publishLink
     * @return
     */
    @RequiresPermissions("work:paper:publish")
    @Log(title = "稿件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/publish")
    @ResponseBody
    public AjaxResult publish(String[] ids, String publishLink, String publishDate) {
        List<WorkPaper> lst = workPaperService.selectWorkPaperByPaperIds(ids);
        Optional<WorkPaper> opt = lst.parallelStream().filter(w -> StringUtils.isEmpty(w.getMediaCreateLogin())).findFirst();
        if (opt.isPresent()) {
            return AjaxResult.error("请先领取稿件！");
        }
        opt = lst.parallelStream().filter(w -> !w.getMediaCreateLogin().equals(getLoginName())).findFirst();
        if (opt.isPresent()) {
            return AjaxResult.error("只能操作自己领取的稿件！");
        }
        workPaperService.selectWorkPaperByPaperIds(ids).forEach(paper -> {
            if (StringUtils.isNotEmpty(publishLink)) {
                if (StringUtils.isNotEmpty(publishDate))
                    paper.setPublishDate(DateUtils.parseDate(publishDate));
                else
                    paper.setPublishDate(DateUtils.getNowDate());
                paper.setPublishLink(publishLink);
            }
            paper.setPaperStatus("4");
            workPaperService.updateWorkPaper(paper);
        });

        return AjaxResult.success();
    }


    /**
     * 批量拒稿
     *
     * @param ids
     * @param
     * @return
     */
    @RequiresPermissions("work:paper:reject")
    @Log(title = "稿件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/reject")
    @ResponseBody
    public AjaxResult reject(String[] ids) {
        List<WorkPaper> lst = workPaperService.selectWorkPaperByPaperIds(ids);
        Optional<WorkPaper> opt = lst.parallelStream().filter(w -> StringUtils.isEmpty(w.getMediaCreateLogin())).findFirst();
        if (opt.isPresent()) {
            return AjaxResult.error("请先领取稿件！");
        }
        opt = lst.parallelStream().filter(w -> !w.getMediaCreateLogin().equals(getLoginName())).findFirst();
        if (opt.isPresent()) {
            return AjaxResult.error("只能操作自己领取的稿件！");
        }
        workPaperService.selectWorkPaperByPaperIds(ids).forEach(paper -> {
            paper.setPaperStatus("3");
            workPaperService.updateWorkPaper(paper);
        });

        return AjaxResult.success();
    }

    /**
     * 批量处理process
     *
     * @param ids
     * @param
     * @return
     */
    @RequiresPermissions("work:paper:process")
    @Log(title = "稿件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/process")
    @ResponseBody
    public AjaxResult process(String[] ids) {
        List<WorkPaper> lst = workPaperService.selectWorkPaperByPaperIds(ids);
        Optional<WorkPaper> opt = lst.parallelStream().filter(w -> StringUtils.isEmpty(w.getMediaCreateLogin())).findFirst();
        if (opt.isPresent()) {
            return AjaxResult.error("请先领取稿件！");
        }
        opt = lst.parallelStream().filter(w -> !w.getMediaCreateLogin().equals(getLoginName())).findFirst();
        if (opt.isPresent()) {
            return AjaxResult.error("只能操作自己领取的稿件！");
        }
        workPaperService.selectWorkPaperByPaperIds(ids).forEach(paper -> {
            paper.setPaperStatus("2");
            workPaperService.updateWorkPaper(paper);
        });

        return AjaxResult.success();
    }

    /**
     * 取消处理
     *
     * @param ids
     * @param
     * @return
     */
    @RequiresPermissions("work:paper:undo")
    @Log(title = "稿件管理", businessType = BusinessType.UPDATE)
    @PostMapping("/undo")
    @ResponseBody
    public AjaxResult undo(String[] ids) {
        List<WorkPaper> lst = workPaperService.selectWorkPaperByPaperIds(ids);
        Optional<WorkPaper> opt = lst.parallelStream().filter(w -> StringUtils.isEmpty(w.getMediaCreateLogin())).findFirst();
        if (opt.isPresent()) {
            return AjaxResult.error("请先领取稿件！");
        }
        opt = lst.parallelStream().filter(w -> !w.getMediaCreateLogin().equals(getLoginName())).findFirst();
        if (opt.isPresent()) {
            return AjaxResult.error("只能操作自己领取的稿件！");
        }
        workPaperService.selectWorkPaperByPaperIds(ids).forEach(paper -> {
            paper.setPaperStatus("1");
            workPaperService.updateWorkPaper(paper);
        });

        return AjaxResult.success();
    }

    @PostMapping("/getprice")
    @ResponseBody
    public AjaxResult getPriceByTyep(Long mediaId, String mediaType, String priceType) {
        BigDecimal price = new BigDecimal(0);
        if (mediaType.equals(MediaType.WB.getCode())) {
            WorkMediaWb workMediaWb = workMediaWbService.selectWorkMediaWbByMediaId(mediaId);
            /*if (priceType.equals(PriceType.WDIRECT.getCode())) {
                price = workMediaWb.getwDirectPrice();
            } else if (priceType.equals(PriceType.WFORWARD.getCode())) {
                price = workMediaWb.getwForwardPrice();
            } else if (priceType.equals(PriceType.WFORWARD.getCode())) {
                price = workMediaWb.getwForwardPrice();
            } else if (priceType.equals(PriceType.DIRECT.getCode())) {
                price = workMediaWb.getDirectPrice();
            } else if (priceType.equals(PriceType.FORWARD.getCode())) {
                price = workMediaWb.getForwardPrice();
            }*/

            price = ICommonEnum.getEnmuByCode(priceType, PriceType.class).getFunction().apply(workMediaWb);
        } else {
            WorkMediaWx workMediaWx = workMediaWxService.selectWorkMediaWxByMediaId(mediaId);
           /* if (priceType.equals(PriceType.LEAD.getCode())) {
                price = workMediaWx.getLeadPrice();
            } else if (priceType.equals(PriceType.SECOND.getCode())) {
                price = workMediaWx.getSecondPrice();
            }*/

            price = ICommonEnum.getEnmuByCode(priceType, PriceType.class).getFunction().apply(workMediaWx);
        }


        //

        return AjaxResult.success(price);
    }

    /**
     * 根据发票ID查询稿件管理列表
     */

    @PostMapping("/invoicelist/{invoiceId}")
    @ResponseBody
    public TableDataInfo invoicelist(@PathVariable("invoiceId") Long invoiceId, WorkPaper workPaper) {
        startPage();
        if (StringUtils.isNotEmpty(workPaper.getCustomerName_()))
            workPaper.setCustomerName(workPaper.getCustomerName_());

        workPaper.setInvoiceId(invoiceId);
        List<WorkPaper> list = workPaperService.selectWorkPaperList(workPaper);
        return getDataTable(list);
    }

    /**
     * 根据请款ID查询稿件管理列表
     */

    @PostMapping("/requestlist/{requestId}")
    @ResponseBody
    public TableDataInfo requestlist(@PathVariable("requestId") Long requestId, WorkPaper workPaper) {
        startPage();

        workPaper.setRequestId(requestId);
        List<WorkPaper> list = workPaperService.selectWorkPaperList(workPaper);
        return getDataTable(list);
    }

    /**
     * 下载模板
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<WorkPaper> util = new ExcelUtil<WorkPaper>(WorkPaper.class);
        return util.importTemplateExcel("普通稿件模板");
    }

    /**
     * 下载模板
     */
    @GetMapping("/importTemplate2")
    @ResponseBody
    public AjaxResult importTemplate2() {
        ExcelUtil<WorkPaper2> util = new ExcelUtil<WorkPaper2>(WorkPaper2.class);
        return util.importTemplateExcel("项目稿件模板");
    }

    /**
     * 导入数据
     */
    @RequiresPermissions("work:paper:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<WorkPaper> util = new ExcelUtil<WorkPaper>(WorkPaper.class);
        List<WorkPaper> paperList = util.importExcel(file.getInputStream());
        String message = importPaper(paperList, updateSupport);
        return AjaxResult.success(message);
    }

    /**
     * 导入稿件数据
     *
     * @param paperList       稿件数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    public String importPaper(List<WorkPaper> paperList, Boolean isUpdateSupport) {
        if (StringUtils.isNull(paperList) || paperList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Long millisecond = Instant.now().toEpochMilli();
        for (WorkPaper paper : paperList) {
            try {

                //TODO 无此稿件，新增
                if (StringUtils.isNull(paper.getMediaName())) {
                    throw new Exception("媒体名称不能为空");
                }
                if (StringUtils.isNull(paper.getPlatform())) {
                    throw new Exception("平台不能为空");
                }
                //paper.getPaperType

                MediaType mediaType = ICommonEnum.getEnmuByCode(paper.getPaperType(), MediaType.class);

                Class aClass = Class.forName(mediaType.getClassName());
                Object instance = Proxy.newProxyInstance(
                        aClass.getClassLoader(),
                        new Class[]{aClass},
                        new BasicCodeDeleteHandler(sqlSession.getMapper(aClass))
                );

                Method method = instance.getClass().getMethod("selectWorkMediaByName", String.class, String.class);
                Long mediaId = (Long) method.invoke(instance, paper.getMediaName(), paper.getPlatform());


                if (mediaId != null) paper.setMediaId(mediaId);
                if (StringUtils.isEmpty(paper.getBelong())) {
                    paper.setCreateBy(getLoginName());
                    paper.setBelong(getUserName());
                } else {
                    paper.setBatchId(millisecond);
                    Object cacheObj = CacheUtils.get("Belong", "Belong_" + paper.getBelong());
                    if (StringUtils.isNotNull(cacheObj)) {
                        SysUser user = StringUtils.cast(cacheObj);
                        paper.setCreateBy(user.getLoginName());
                    } else {
                        SysUser user = sysUserService.selectUserByUserName(paper.getBelong());
                        CacheUtils.put("Belong", "Belong_" + paper.getBelong(), user);
                        paper.setCreateBy(user.getLoginName());
                    }
                }
                if (StringUtils.isNotEmpty(paper.getMediaCreate())) {
                    Object cacheObj = CacheUtils.get("MediaCreate", "MediaCreate_" + paper.getMediaCreate());
                    if (StringUtils.isNotNull(cacheObj)) {
                        SysUser user = StringUtils.cast(cacheObj);
                        paper.setMediaCreateLogin(user.getLoginName());
                    } else {
                        SysUser user = sysUserService.selectUserByUserName(paper.getMediaCreate());
                        CacheUtils.put("MediaCreate", "MediaCreate_" + paper.getMediaCreate(), user);
                        paper.setMediaCreateLogin(user.getLoginName());
                    }
                }
                workPaperService.insertWorkPaper(paper);
                successNum++;
                successMsg.append("<br/>" + successNum + "、稿件：" + paper.getPaperName() + " 稿件类型：" + ICommonEnum.getEnmuByCode(paper.getPaperType(), MediaType.class).getInfo() + " 媒体:" + paper.getMediaName() + " 平台:" + paper.getPlatform() + " 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、稿件 " + paper.getPaperName() + " 稿件类型：" + ICommonEnum.getEnmuByCode(paper.getPaperType(), MediaType.class).getInfo() + " 媒体:" + paper.getMediaName() + " 平台:" + paper.getPlatform() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 查询销账部分稿件弹窗页面
     */
    /*@RequiresPermissions("work:paper:cancel")*/
    @PostMapping("/cancel/{incomingId}/{invoiceId}")
    @ResponseBody
    public TableDataInfo cancel(@PathVariable("incomingId") Long incomingId, @PathVariable("invoiceId") Long invoiceId, WorkPaper workPaper) {
        startPage();
        Map<String, Object> map = new HashMap<>();
        map.put("incomingId", incomingId);
        map.put("invoiceId", invoiceId);
        if (StringUtils.isNotEmpty(workPaper.getPaperName())) map.put("paperName", workPaper.getPaperName());
        if (StringUtils.isNotEmpty(workPaper.getCustomerName())) map.put("customerName", workPaper.getCustomerName());
        List<WorkPaper> list = workPaperService.selectPaperNoCancel(map);
        return getDataTable(list);
    }


    @RequestMapping("/off/{incomingId}")
    @ResponseBody
    public TableDataInfo noOffList(@PathVariable("incomingId") Long incomingId, ModelMap mmap) {

        Map<String, Object> map = new HashMap<>();
        map.put("incomingId",incomingId);
        map.put("invoiceId",0L);
        List<WorkPaper> list = workPaperService.selectPaperByCancel(map);
        return getDataTable(list);
    }
}
